/*
 * socket.c
 *
 *  Created on: 2009-5-28
 *      Author: root
 */

#include"mysocket.h"
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>


int socket(){
	static int i=0;
	int rv;
	msg message;
	sockmsg retmsg;
	memset(&message,0,sizeof(msg));
	message.mtype=MSG_USR_SOCK;
	message.pid=getpid();
	do{
		fprintf(message.buf,"fifo%ld%d",(long)pid,i++);
		rv=mkfifo(message.buf,PERM_FILE);
		if(rv<0&&errno!=EEXIST){
			fprintf(stderr,"can not create fifo in socket\n");
			return -1;
		}
	}while(rv<0&&errno==EEXIST);
	int fd=open(message.buf,O_RDONLY);
	if(fd<0)
		return -1;
	message.msgqid=processqid;
	message.sock=fd;
	if(msgsnd(tcpipstackqid,&message,sizeof(msg)-sizeof(long),0,0)<0){
		fprintf(stderr,"can not comunicate with tcp/ip stack\n");
		return -1;
	}
	if((rv=msgrcv(processqid,&retmsg,sizeof(sockmsg)-sizeof(long),0,0))<0){
		fprintf(stderr,"tcp/ip stack does not work!\n");
		return -1;
	}
	return retmsg.ret;
}
